import {Injectable} from "@angular/core";
import {Storage} from "@ionic/storage";
import {SqliteService} from "./sqlite.service";
import {AppService} from "./app.service";
import {UtilService} from "./util.service";
import {ResDataModel} from "../models/res-data-model";
import {UserInfoService} from "./userInfo.service";

@Injectable()
export class MessageService {
  constructor(private storage:Storage,
              private sqliteService:SqliteService,
              private userInfoService:UserInfoService,
              private appService:AppService){

  }

  //消息同步
  syncMsg(callback?){

    this.storage.get("latestMsgTime").then(value => {
      let postData:any = {
        "state":"0",
      };

      if(value!=null){//不为空，进行增量同步
        postData.afterTime = value;
      } else {//为空，进行全量同步
        //storage.set("MsgSyncTime",true);
      }
      //获取未读消息
      this.appService.httpPost('AppMessageNewCtrl_list',postData,null,(res:ResDataModel)=>{
        var list:any[] = res.datas[0].trs;
        if(list.length > 0){//若存在未读消息，存入本地数据库

          //记录最新一条未读消息的时间
          var latestMsgTime = list[0].tds.sendTime.value;
          this.storage.set("latestMsgTime",UtilService.toDateString(latestMsgTime));

          //var sqlStatements: Array<string | string[] | any> = [];
          list.forEach(value => {
            var cId = value.tds.cId.value;
            var content = value.tds.content.value;
            var contentSize = value.tds.contentSize.value;
            var contentType = value.tds.contentType.value;
            var msgId = value.tds.msgId.value;
            var msgSrcType = value.tds.msgSrcType.value;
            var msgType = value.tds.msgType.value;
            var readTime = UtilService.toDateString(value.tds.readTime.value);
            var receiveTime = UtilService.toDateString(value.tds.receiveTime.value);
            var senderId = value.tds.senderId.value;
            var senderType = value.tds.senderType.value;
            var sendTime = UtilService.toDateString(value.tds.sendTime.value);
            var state = value.tds.state.value;
            var topic = value.tds.topic.value;
            var updateTime = UtilService.toDateString(value.tds.updateTime.value);
            var userId = value.tds.userId.value;
            var xtbm = value.tds.xtbm.value;
            var ywbldz = value.tds.ywbldz.value;
            var ywztlx = value.tds.ywztlx.value;
            var yxbz = value.tds.yxbz.value;
            var sql = 'Insert INTO app_messages values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)';
            var param:Array<string> = [cId,topic,contentType,content,contentSize,msgId,msgType,msgSrcType,userId,senderId,senderType,sendTime,receiveTime,readTime,updateTime,state,xtbm,ywbldz,ywztlx,yxbz];
            //执行插入
            this.sqliteService.execSql(sql,param);
            //sqlStatements.push([sql,param]);
          })
          //执行批量插入
/*          var db:SQLiteObject = this.sqliteService.db;
          db.sqlBatch(sqlStatements).then(result=>{
            console.log('insert sucess');
          },err=>{
            console.error(err);
          })*/
        }
        //执行回调
        if(callback){
          callback();
        }
      })

    })
  }

  //消息状态变更
  updateMsgStatus(item:any,sync?:boolean){
    var sql = 'Update app_messages set state = ? where cId = ?';
    this.sqliteService.execSql(sql,[item.state,item.cId]).then(res=>{
      console.log(res);
    },err=>{
      console.error(err);
    }).catch(err=>{
      console.error(err);
    });
    if(sync){//将状态回写服务器
      var postData = {
        cId:item.cId,
        state:item.state
      };
      this.appService.httpPost('AppMessageNewCtrl_setMessageStatus',postData,null,(data)=>{
          console.log(data);
      })
    }
  }

  //消息删除
  delMsg(item:any,sync?:boolean){
    var sql = 'delete from app_messages where cId = ?';
    this.sqliteService.execSql(sql,[item.cId]).then(res=>{
      console.log(res);
    },err=>{
      console.error(err);
    }).catch(err=>{
      console.error(err);
    });
    if(sync){//将状态回写服务器
/*      var postData = {
        cId:item.cId,
        state:item.state
      };
      this.appService.httpPost('AppMessageNewCtrl_setMessageStatus',{},postData,(data)=>{
        console.log(data);
      })*/
    }
  }

  //建表
  creatMsgTable(){
    var sql =`
      CREATE TABLE
      IF
        NOT EXISTS app_messages (
        cId VARCHAR2 ( 32 ) PRIMARY KEY,
        topic VARCHAR2 ( 50 ) NOT NULL,
        content_type VARCHAR2 ( 2 ) NOT NULL,
        content VARCHAR2 ( 2000 ) NOT NULL,
        contentSize NUMBER ( 10 ),
        msgId VARCHAR2 ( 32 ) NOT NULL,
        msgType VARCHAR2 ( 2 ),
        msgSrcType VARCHAR2 ( 2 ),
        user_id VARCHAR2 ( 32 ) NOT NULL,
        senderId VARCHAR2 ( 32 ) NOT NULL,
        senderType VARCHAR2 ( 2 ) NOT NULL,
        sendTime DATE,
        receiveTime DATE,
        readTime DATE,
        updateTime DATE,
        state VARCHAR2 ( 2 ),
        xtbm VARCHAR2 ( 32 ),
        ywbldz VARCHAR2 ( 100 ),
        ywztlx VARCHAR2 ( 2 ),
        yxbz VARCHAR2 ( 1 ));`
    this.sqliteService.execSql(sql,[]).then(data=>{
      console.log(data)
    }).catch(err =>{
      console.log(err);
    })
  }

  /**
   * 获取当前登录人的消息列表
   * @param pageParam
   * @returns {Promise<any>}
   */
  getMsgList(pageParam?:any): Promise<any>{
    var userId = this.userInfoService.user.userId;
    var sql = 'select * from app_messages where user_id = ? order by sendTime desc';
    var params:Array<any> = [];
    params.push(userId);

    if(!pageParam){
      //sql = 'select * from app_messages order by sendTime desc';
    } else {
      //sqlite不支持rownum的用法，rowid为原表的行号，并非结果集的行号，此处暂时作废
/*      sql = 'select * from (select *,rowid from app_messages order by sendTime desc) t where t.rowid between ? and ?';
      var beginRowId = (pageParam.pageNum-1)*pageParam.rows+1;
      var endRowId = pageParam.pageNum*pageParam.rows;
      params.push(beginRowId);
      params.push(endRowId);*/
    }

    return new Promise((resolve, reject) => {

      this.sqliteService.execSql(sql,params).then((res)=>{
        resolve(res.res);
      },(res)=>{
        console.error(res);
        reject(res.err);
      }).catch(err=>{
        reject(err.err);
      })
    })

  }

  /**
   * 返回未读消息数量
   * @returns {Promise<any>}
   */
  getUnReadMsgCount(): Promise<any> {
    return new Promise((resolve, reject) => {
      var sql = "select count(1) as countNum from app_messages where state = '0'";
      this.sqliteService.execSql(sql,[]).then(res=>{
        console.log(res);
        resolve(res.res);
      },res=>{
        console.error(res);
        reject(res.err);
      })
    })
  }

}
